<?php
class Base extends CI_Controller {
	
	private $vars;
	private $layout;
	private $messages;
	private $validation_errors;
	
	/**
	 * @var CI_Session
	 */
	public $session;
	
	/**
	 * @var CI_Form_validation
	 */
	public $form_validation;
	
	/**
	 * @var Security_Manager
	 */
	public $security_manager;
	
	public function __construct() {
		parent::__construct();
		$this->vars = array();
		$this->messages = array('error' => array(), 'success' => array());
		$this->layout = 'layouts/template';
		
		if (!Security_Manager::mvc_authorization()) {
			return $this->redirect($this->security_manager->get_redirect_url());
		}
		
		$this->setup_messages();
		
		$this->lang->load('base');
	}
	
	protected function get_param($name, $default = null) {
		return (isset($_REQUEST[$name])) ? $_REQUEST[$name] : $default;
	}
	
	protected function set_variable($name, $value) {
		$this->vars[$name] = $value;
	}
	
	protected function add_error_message($message) {
		$this->messages['error'][] = $message;
	}
	
	protected function add_success_message($message) {
		$this->messages['success'][] = $message;
	}
	
	protected function redirect($url) {
		$this->session->set_userdata('messages', $this->messages);
		$this->session->set_userdata('validation_errros', validation_errors());
		redirect($url);
	}
	
	protected function render($page) {
		$this->set_variable('__layout_page__', 
				APPPATH . 'views/pages/' . strtolower(get_class($this)) 
				.'/'. $page);
		$this->set_variable('__base_url__', base_url());
		$this->set_variable('__messages_error__', $this->messages['error']);
		$this->set_variable('__messages_success__', $this->messages['success']);
		
		if (!empty($this->validation_errors)) {
			$this->set_variable('__validation_errors__', 
				$this->validation_errors . validation_errors());
		} else {
			$this->set_variable('__validation_errors__', validation_errors());
		}
		
		$this->load->view($this->layout, $this->vars);
	}
	
	protected function is_post() {
		return $_SERVER['REQUEST_METHOD'] == 'POST';
	}
	
	private function setup_messages() {
		$messages = $this->session->userdata('messages');
		if (!empty($messages)) {
			$this->messages = $messages;
		}
		
		$validation_errors = $this->session->userdata('validation_errros');
		if (!empty($validation_errors)) {
			$this->validation_errors =$validation_errors;
		}
		
		$this->session->unset_userdata('messages');
		$this->session->unset_userdata('validation_errros');
	}
}